package parser;

import java.io.PrintWriter;

import lexer.Token;
import lexer.TokenType;

/**
 * Parses a primary expression from the TokenIterator Grammar: (identifier) or
 * (number)
 */
public class LogoPrimaryExpression extends LogoExpression {

	String identifierValue = null;
	Integer intValue = null;

	/**
	 * Parses a primary expression from the TokenIterator
	 */
	public LogoPrimaryExpression(TokenIterator it) throws LogoParseException {
		if (!it.hasNext()) {
			throw new LogoParseException("Unexpectedly reached end of program");
		}

		Token token = it.next();

		if (token.getType() == TokenType.IDENTIFIER) {
			identifierValue = token.getContents();
		} else if (token.getType() == TokenType.NUMBER) {
			try {
				intValue = Integer.parseInt(token.getContents());
			} catch (NumberFormatException e) {
				throw new LogoParseException(token, "Invalid number: "
						+ token.getContents());
			}
		} else {
			throw new LogoParseSyntaxException(token, "IDENTIFIER or NUMBER");
		}
	}

	@Override
	public void resolveIdentifiers(LogoScope scope) throws LogoParseException {
		if (identifierValue != null) {
			if (scope.getTypeOf(identifierValue) == LogoIdentifierType.VARIABLE) {
				return;
			} else if (scope.getTypeOf(identifierValue) == LogoIdentifierType.PROCEDURE) {
				throw new LogoParseException("Used Identifier " + identifierValue + " as type VARIABLE when " + identifierValue + " defined as PROCEDURE");
			} else {
				throw new LogoParseException("Unindentied identifier " + identifierValue);
			}
		}
	}

	/**
	 * Example output: 5 or LEVEL
	 */
	@Override
	public void generatePostScriptCode(PrintWriter stream) {
		if (identifierValue == null) {
			stream.print(intValue + " ");
		} else {
			stream.print("Arg" + " ");
		}
	}

}
